97. Interleaving String - LeetCode Solution


Dynamic programming

Python Code:

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        dp = []
        
        if len(s1) + len(s2) != len(s3):
            return False
        

        for i in range(len(s1)+1):
            a = []

            for j in range(len(s2)+1):
                a.append(-1)
            dp.append(a)


        def trav(s1, s2, s3, ptr1, ptr2, ptr3):
            if ptr3 == len(s3):
                return True

            if dp[ptr1][ptr2] != -1:
                return dp[ptr1][ptr2]


            a =b= False
            if ptr1 != len(s1) and s1[ptr1] == s3[ptr3]:
                a = trav(s1, s2, s3, ptr1+1, ptr2, ptr3 + 1)
            if ptr2 != len(s2)  and s2[ptr2] == s3[ptr3]:
                b = trav(s1, s2, s3, ptr1, ptr2 + 1, ptr3 + 1)

            dp[ptr1][ptr2] = a or b
            return dp[ptr1][ptr2]


        return trav(s1, s2, s3, 0, 0, 0)


Comments

Submit
0 Comments
More Questions

1279A - New Year Garland
1279B - Verse For Santa
202A - LLPS
978A - Remove Duplicates
1304A - Two Rabbits
225A - Dice Tower
1660D - Maximum Product Strikes Back
1513A - Array and Peaks
1251B - Binary Palindromes
768B - Code For 1
363B - Fence
991B - Getting an A
246A - Buggy Sorting
884A - Book Reading
1180A - Alex and a Rhombus
445A - DZY Loves Chessboard
1372A - Omkar and Completion
159D - Palindrome pairs
981B - Businessmen Problems
1668A - Direction Change
1667B - Optimal Partition
1668B - Social Distance
88B - Keyboard
580B - Kefa and Company
960A - Check the string
1220A - Cards
897A - Scarborough Fair
1433B - Yet Another Bookshelf
1283B - Candies Division
1451B - Non-Substring Subsequence